<?php
namespace Modules\Activity\Http\Controllers\Client\Fudai;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Fudai\Activity;
use \Modules\Activity\Entities\ActivityOrder as Order;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;
use Setting;


// 福袋订单
class OrderController extends Controller
{
    // 预览订单
    public function preview(Request $req) 
    {
        $rule = [
            // 'page_uuid' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        // 是否开启商城支付
        if (!@Setting::get('sys_pay_enable')['is_fudai_enabled']) {
            ThrowException::Conflict(@Setting::get('sys_pay_enable')['fudai_tips'] ?: '系统维护中~');
        }

        $user = Auth::requireLoginUser();

        if ($req->input('page_uuid')) {
            $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

            // 福袋
            $activity = Activity::getEntity([
                'id' => $cached['fudai_id']
            ]);
        }
        elseif ($req->input('uuid')) {
            // 福袋
            $activity = Activity::getEntity([
                'uuid' => $req->input('uuid')
            ]);
        }
        else {
            return [];
        }

        if ($activity->isOffStock()) {
            ThrowException::Conflict('此福袋已下架~');
        }

        // 基础款是否已售空
        if ($activity->skus()->where('level', 1)->sum('stock') <= 0) {
            // 下架
            $activity->update([
                'status' => 0
            ]);
            ThrowException::Conflict('此款已售罄~');
        }

        // 购买总数
        $total = $req->total;

        // 检查是否超出限售
        Activity::checkSaleLimit($total);

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
        ]);

        return $order->generatePreviewResponse($user);
    }

    // 创建订单
    public function store(Request $req) 
    {
        $rule = [
            // 'page_uuid' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        // 是否开启商城支付
        if (!@Setting::get('sys_pay_enable')['is_fudai_enabled']) {
            ThrowException::Conflict(@Setting::get('sys_pay_enable')['fudai_tips'] ?: '系统维护中~');
        }

        $user = Auth::requireLoginUser();
        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_order', 1);

        if ($req->input('page_uuid')) {
            $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

            // 福袋
            $activity = Activity::getEntity([
                'id' => $cached['fudai_id']
            ]);
        }
        elseif ($req->input('uuid')) {
            // 福袋
            $activity = Activity::getEntity([
                'uuid' => $req->input('uuid')
            ]);
        }
        else {
            return [];
        }

        if ($activity->isOffStock()) {
            ThrowException::Conflict('此福袋已下架~');
        }

        // 基础款是否已售空
        if ($activity->skus()->where('level', 1)->sum('stock') <= 0) {
        	// 下架
        	$activity->update([
        		'status' => 0
        	]);
        	ThrowException::Conflict('此款已售罄~');
        }

        // 购买总数
        $total = $req->total;

        // 检查是否超出限售
        Activity::checkSaleLimit($total);

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');

        $sharer = 0;
        if ( $req->input('sharer') ){
            $s = DB::table('users')->where('uuid', $req->sharer)->first();
            $s_init = object_to_array($s);
            $sharer = $s_init['id'];
        }

        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
            'sharer' => $sharer,
        ]);

        // 使用免费次数兑换
        if ($req->input('is_use_free_ticket') && $total === 1) {
            $activity->ticketOut($user, 1);
            $order->useFreeTicket();
        }

        $order->createAll();

        DB::commit();

        // 返回订单内容
        return $order->generateResponse();
    }

    // 试一试
    public function try(Request $req) 
    {
        $rule = [
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        if ($req->input('page_uuid')) {
            $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

            // 福袋
            $activity = Activity::getEntity([
                'id' => $cached['fudai_id']
            ]);
        }
        elseif ($req->input('uuid')) {
            $activity = Activity::getEntity([
                'uuid' => $req->uuid
            ]);
        }

        // 购买总数
        $total = $req->total;

        // 仅仅
        DB::beginTransaction();

        // 取出sku
        $skuMaps = $activity->pickLuckySkusForTry($total, $user, null) ?: ThrowException::Conflict('未抽出商品~');

        $list = [];

        // 此处不要提交到数据库保存
        foreach ($skuMaps as $skuMap) {
            $sku = $skuMap['skuable'];
            array_push($list, [
                "title" => $sku->title,
                "number" => $sku->number,
                "thumb" => $sku->thumb,
                "money_price" => $sku->money_price,       // 价值 (人民币)
                "total" => $skuMap['total'],                 // 中奖数量
            ]);
        }

        $uuid = 'try_' . uniqid();

        $cached = [
            'sku_type' => 'fudai_sku',
            'sku_id' => $skuMaps[0]['skuable']->id,
            'skus' => $list
        ];
        Cache::put($uuid, $cached, 180);

        return [
            'package_uuid' => $uuid
        ];

    }
}
